package com.mvc.dao;


import com.mvc.entity.User;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.*;

/**
 * Created by zhudong on 2016/9/4.
 */
@Service
@Transactional
public class UserDao extends BaseDao{

    @Autowired
    private DepartmentDao departmentDao;

    public List<User> getAll(){
        Session session = getSession();
        String hql = "from User";
        return session.createQuery(hql).list();
    }

    public User getById(Integer id){
        Session session = getSession();
        return (User)session.get(User.class,id);
    }

    public void save(User user){
        Session session = getSession();
//        if(user.getId()!=null){
        user.setDepartment(departmentDao.getById(user.getDepartment().getId()));
//        }
        session.saveOrUpdate(user);
    }

    public void delete(Integer id){
        Session session = getSession();
        String hql = "delete from User u where u.id=:id";
        session.createQuery(hql).setInteger("id",id).executeUpdate();
    }

}
